package com.rndemo.rn.api;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Argument;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.rndemo.RNCommonActivity;

import java.util.WeakHashMap;

/**
 * Created by Administrator on 2018/4/15.
 */
public class NavigationModule extends ReactContextBaseJavaModule{
    private WeakHashMap mWeakHashMap = new WeakHashMap();
    private ActivityEventListener listener = new ActivityEventListener() {
        @Override
        public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
            try {
                Object remove = mWeakHashMap.remove(activity);
                if (remove!=null&&remove instanceof Promise){
                    WritableMap result = Argument.createMap();
                    if(data!=null){
                        Bundle temp = data.getExtras();
                        result = Argument.makeNativeMap(temp);
                    }
                    result.putInt("requestCode",requestCode);
                    result.putInt("resultCode",resultCode);
                    ((Promise)remove).resolve(result);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        @Override
        public void onNewIntent(Intent intent) {
        }
    };

    public NavigationModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "NavigatorIOS";
    }

    @Override
    public void initialize() {
        super.initialize();
        ReactInstanceManager reactInstanceManager = ((ReactApplication) getReactApplicationContext().getApplicationContext()).getReactNativeHost().getReactInstanceManager();
        reactInstanceManager.getCurrentReactContext().addActivityEventListener(listener);
    }

    @Override
    public void onCatalystInstanceDestroy() {
        super.onCatalystInstanceDestroy();
        ReactInstanceManager reactInstanceManager = ((ReactApplication) getReactApplicationContext().getApplicationContext()).getReactNativeHost().getReactInstanceManager();
        if(reactInstanceManager.getCurrentReactContext()!=null){
            reactInstanceManager.getCurrentReactContext().removeActivityEventListener(listener);
        }
    }

    @Override
    public boolean canOverrideExistingModule() {
        return true;
    }

    /**
     *  start
     *  {
     *  activity,requestCode, //先走 activity
     *  component
     *  }
     * @param promise
     */
    @ReactMethod
    public void push(final ReadableMap map, final Promise promise){
        getReactApplicationContext().runOnUiQueueThread(new Runnable() {
            @Override
            public void run() {
                Bundle bundle = Argument.toBundle(map);
                String activity = null;
                if(bundle != null){
                    activity = bundle.getString("activity");
                }
                if(activity!=null){//如果有activity 则启动 这个activity
                    try {
                        Class toActivity = Class.forName(activity);
                        Intent intent = new Intent(getCurrentActivity().getApplicationContext(),toActivity);
                        intent.putExtra("activity",activity);
                        intent.putExtras(bundle);
                        getCurrentActivity().startActivityForResult(intent,(int) bundle.getInt("requestCode",0),bundle);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        RNCommonActivity.startForResult(getCurrentActivity(), bundle,null);
                    }
                }else{
                    RNCommonActivity.startForResult(getCurrentActivity(), bundle,null);
                }
                mWeakHashMap.put(getCurrentActivity(),promise);
            }
        });
    }

    /**
     * finish
     * @param count
     */
    @ReactMethod
    public void pop(final int count,final ReadableMap map){
        if(count<1){
            return;
        }
        final Handler handler = new Handler(Looper.getMainLooper());
        Runnable run = new Runnable() {
            private int i = count;
            private Activity tempActivity;
            @Override
            public void run() {
                Activity currentActivity = getCurrentActivity();
                if(currentActivity == tempActivity){
                    handler.postDelayed(this,100);
                }else if(currentActivity!=null){
                    tempActivity = currentActivity;
                    Intent intent = new Intent();
                    intent.putExtras(Argument.toBundle(map));
                    currentActivity.setResult(Activity.RESULT_CANCELED,intent);
                    currentActivity.finish();
                    i--;
                    if(i>0){
                        handler.post(this);
                    }else{
                        tempActivity = null;
                    }
                }
            }
        };
        handler.post(run);
    }


    @ReactMethod
    public void replace(String rnName, Promise promise){

    }




}
